<template>
	<!-- 以下是弹窗内容 -->
	<a-modal
		v-model:open="visible"
		title="商品选择"
		:width="1200"
		:mask-closable="false"
		:destroy-on-close="true"
		@ok="handleOk"
		@cancel="handleClose"
	>
		<a-row :gutter="10">
			<a-col :span="4">
				<a-card size="small" :loading="cardLoading" class="selectorTreeDiv">
					<a-tree
						v-if="treeData"
						v-model:expandedKeys="defaultExpandedKeys"
						:tree-data="treeData"
						:field-names="treeFieldNames"
						@select="treeSelect"
					>
					</a-tree>
				</a-card>
			</a-col>
			<a-col :span="12">
				<div class="table-operator xn-mb10">
					<a-form ref="searchFormRef" name="advanced_search" class="ant-advanced-search-form" :model="searchFormState">
						<a-row :gutter="24">
							<a-col :span="12">
								<a-form-item name="searchKey">
									<a-input v-model:value="searchFormState.searchKey" placeholder="请输入名称、条码、拼音码" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-button type="primary" class="xn-mr-10" @click="loadData()"> 查询 </a-button>
								<a-button @click="reset()"> 重置 </a-button>
							</a-col>
						</a-row>
					</a-form>
				</div>
				<div class="user-table">
					<a-table
						ref="tableRef"
						size="small"
						:columns="commons"
						:data-source="tableData"
						:expand-row-by-click="true"
						:loading="pageLoading"
						bordered
						:pagination="false"
					>
						<template #title>
							<span>待选择列表 {{ tableRecordNum }} 条</span>
							<div v-if="!radioModel" class="xn-fdr">
								<a-button type="dashed" size="small" @click="addAllPageRecord">添加当前数据</a-button>
							</div>
							<div  class="xn-fdr" style="margin-right: 20px" v-show="props.productionSupplier">
								<a-checkbox v-model:checked="searchFormState.filterSupplier"  @change="filterSupplierChange">仅显示当前供应商的产品</a-checkbox>
							</div>
						</template>
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'avatar'">
								<a-avatar :src="record.avatar" style="margin-bottom: -5px; margin-top: -5px" />
							</template>
							<template v-if="column.dataIndex === 'action'">
								<a-button type="dashed" size="small" @click="addRecord(record)"><PlusOutlined /></a-button>
							</template>
							<template v-if="column.dataIndex === 'category'">
								{{ $TOOL.dictTypeData('ROLE_CATEGORY', record.category) }}
							</template>
						</template>
					</a-table>
					<div class="mt-2">
						<a-pagination
							v-if="!isEmpty(tableData)"
							v-model:current="current"
							v-model:page-size="pageSize"
							:total="total"
							size="small"
							showSizeChanger
							@change="paginationChange"
						/>
					</div>
				</div>
			</a-col>
			<a-col :span="8">
				<div class="user-table">
					<a-table
						ref="selectedTable"
						size="small"
						:columns="selectedCommons"
						:data-source="selectedData"
						:expand-row-by-click="true"
						:loading="selectedTableListLoading"
						bordered
					>
						<template #title>
							<span>已选择: {{ selectedData.length }}</span>
							<div v-if="!radioModel" class="xn-fdr">
								<a-button type="dashed" danger size="small" @click="delAllRecord">全部移除</a-button>
							</div>
						</template>
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'productionLocationIds'">
								<a-select
									v-model:value="record.productionLocationIds"
									:options="locationOptions"
									style="width:100%"
									:bordered="false"
									:showArrow="false"
									show-search
									mode="multiple"
									allow-clear
									placeholder="请选择库位"
									:field-names="{
										label:'locationName',
										value:'id'
									}"
									:filter-option="locationFilterOption"
									@change="locationChange"
									@search = "handleSearch"
									@popupScroll="handlePopupScroll"
								>
								</a-select>
							</template>
							<template v-if="column.dataIndex === 'action'">
								<a-button type="dashed" danger size="small" @click="delRecord(record)"><MinusOutlined /></a-button>
							</template>
						</template>
					</a-table>
				</div>
			</a-col>
		</a-row>
	</a-modal>
</template>

<script setup name="userSelector">
	import { message } from 'ant-design-vue'
	import { remove, isEmpty, cloneDeep } from 'lodash-es'
	import userCenterApi from '@/api/sys/userCenterApi'
	import supplierCarrierApi from "@/api/supplier/base/supplierCarrierApi";
	import supplierStoresLocationApi from "@/api/supplier/warehouse/supplierStoresLocationApi";
	import supplierProductionsApi from "@/api/supplier/base/supplierProductionsApi";
	// 弹窗是否打开
	const visible = ref(false)
	// 主表格common
	const commons = [
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 50
		},
		{
			title: '条码',
			dataIndex: 'productionBarcode',
		},
		{
			title: '商品名称',
			dataIndex: 'productionName',
		},
		{
			title: '单位',
			dataIndex: 'productionUnit',
		},
		{
			title: '单价',
			dataIndex: 'productionPriceSale'
		},
		{
			title: '库存',
			dataIndex: 'productionStock'
		}
	]
	// 选中表格的表格common
	const selectedCommons = [
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 50
		},
		{
			title: '商品名称',
			dataIndex: 'productionName',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'productionUnit',
			ellipsis: true
		},
		{
			title: '库位',
			dataIndex: 'productionLocationIds',
			ellipsis: true,
			align: 'center',
			width: 150
		}
	]
	const props = defineProps({
		radioModel: { //是否仅选取一个
			type: Boolean,
			default: () => false
		},
		dataIsConverterFlw: {
			type: Boolean,
			default: () => false
		},
		categoriesTreeApi: {
			type: Function
		},
		productionsPageApi: {
			type: Function
		},
		productionsListByIdListApi: {
			type: Function
		},
		value: {
			default: () => ''
		},
		dataType: {
			type: String,
			default: () => 'string'
		},
		productionsShow: {
			type: Boolean,
			default: () => true
		},
		addShow: {
			type: Boolean,
			default: () => true
		},
		locationStorage:{
			type: String,
			default: () => null
		},
		productionSupplier: {
			type: String,
			default: () => null
		}
	})
	//定义库位下拉框
	const locationOptions = ref([])
	const searchParams = ref({
		current: 1,
		size:10,
		pages:0,
		total:0,
		searchKey:"",
		locationStore: props.locationStorage,
	})
	const getLocationOptions = (isScroll=false) => {
		searchParams.value.locationStore = props.locationStorage
		supplierStoresLocationApi.supplierStoresLocationPage(searchParams.value).then((res) => {
			searchParams.value.pages = res.pages //共多少页
			searchParams.value.current = res.current//当前页
			searchParams.value.total = res.total
			if (isScroll==false){ //如果不是下拉触发，则清空原有的数据源重新加载
				locationOptions.value = []
			}
			//将本次拉取的数据与原有的数据源合并
			locationOptions.value = [...locationOptions.value,...res.records]
		})
	}
	//下拉触发
	const handlePopupScroll = (e)=>{
		const { target } = e;
		const { scrollTop, scrollHeight, clientHeight } = target;
		if (scrollTop + 2 + clientHeight >= scrollHeight) {
			// 已经到达底部，触发分页逻辑
			// todo 这里就可以触发加载下一页请求  具体函数根据当前业务需求来定
			if(searchParams.value.current<searchParams.value.pages){//后面还有
				searchParams.value.current = searchParams.value.current +1
				getLocationOptions(true);//这里是下拉加载，不清空原来的数据
			}
		}
	}
	//根据手输入进行过滤
	const locationFilterOption = (input,locationOptions) =>{
		return `${locationOptions.locationName}`.includes(`${input || ''}`)
	}
	//根据输入的关键字到后端查找，并列新数据源
	const handleSearch = (value)=>{
		searchParams.value.searchKey = value
		searchParams.value.current = 1
		getLocationOptions(false)
	}
	const locationChange=()=>{//当选定数据后，根据ID到后端查询该账户的详情，并有选择地赋给页控件
		searchParams.value = {
			current: 1,
			size:10,
			pages:0,
			total:0,
			searchKey:"",
			locationStore: props.locationStorage
		}
		getLocationOptions(false)
	}

	// 主表格的ref 名称
	const tableRef = ref()
	// 选中表格的ref 名称
	const selectedTable = ref()
	const tableRecordNum = ref()
	const searchFormState = ref({})
	const searchFormRef = ref()
	const cardLoading = ref(true)
	const pageLoading = ref(false)
	const selectedTableListLoading = ref(false)
	// 替换treeNode 中 title,key,children
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	// 获取分类树数据
	const treeData = ref()
	//  默认展开二级树的节点id
	const defaultExpandedKeys = ref([])
	const emit = defineEmits(['update:value', 'onBack'])
	const tableData = ref([])
	const selectedData = ref([])
	const recordIds = ref([])
	// 分页相关
	const current = ref(0) // 当前页数
	const pageSize = ref(20) // 每页条数
	const total = ref(0) // 数据总数
	// 获取选中列表的api
	const productionsListByIdList = (param) => {
		if (typeof props.productionsListByIdListApi === 'function') {
			return props.productionsListByIdListApi(param)
		} else {
			return supplierProductionsApi.supplierProductionsPage(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}
	// 打开弹框
	const showProductionsPlusModal = (ids = []) => {
		openModal()
	}

	const openModal = () => {
		if (typeof props.categoriesTreeApi !== 'function') {
			message.warning('未配置选择器需要的categoriesTreeApi接口')
			return
		}
		if (typeof props.productionsPageApi !== 'function') {
			message.warning('未配置选择器需要的productionsPageApi接口')
			return
		}

		visible.value = true
		// 获取机构树
		props
			.categoriesTreeApi()
			.then((data) => {
				if (data !== null) {
					treeData.value = data
					// 默认展开2级
					treeData.value.forEach((item) => {
						// 因为0的顶级
						if (item.parentId === '0') {
							defaultExpandedKeys.value.push(item.id)
							// 取到下级ID
							if (item.children) {
								item.children.forEach((items) => {
									defaultExpandedKeys.value.push(items.id)
								})
							}
						}
					})
				}
			})
			.finally(() => {
				cardLoading.value = false
			})
		searchFormState.value.size = pageSize.value
		searchFormState.value.filterSupplier = props.productionSupplier !== null
		loadData()
		//库位下拉数据源
		getLocationOptions(false)
		if (isEmpty(recordIds.value)) {
			return
		}
		const param = {
			idList: recordIds.value
		}
		selectedTableListLoading.value = true
		productionsListByIdList(param)
			.then((data) => {
				selectedData.value = data
			})
			.finally(() => {
				selectedTableListLoading.value = false
			})
	}
	// 查询主表格数据
	const loadData = () => {
		pageLoading.value = true
		searchFormState.value.locationStorage = props.locationStorage  //带仓库库位参数
		searchFormState.value.productionSupplier  = searchFormState.value.filterSupplier ? props.productionSupplier : null //如果勾选，则传供应商信息
		props
			.productionsPageApi(searchFormState.value)
			.then((data) => {
				current.value = data.current
				// pageSize.value = data.size
				total.value = data.total
				// 重置、赋值
				tableData.value = []
				tableRecordNum.value = 0
				tableData.value = data.records
				if (data.records) {
					tableRecordNum.value = data.records.length
				} else {
					tableRecordNum.value = 0
				}
			})
			.finally(() => {
				pageLoading.value = false
			})
	}
	// pageSize改变回调分页事件
	const paginationChange = (page, pageSize) => {
		searchFormState.value.current = page
		searchFormState.value.size = pageSize
		loadData()
	}
	const judge = () => {
		return !(props.radioModel && selectedData.value.length > 0)
	}
	// 添加记录
	const addRecord = (record) => {

		if (!judge()) {
			message.warning('只可选择一条')
			return
		}
		const selectedRecord = selectedData.value.filter((item) => item.id === record.id)
		if (selectedRecord.length === 0) {
			selectedData.value.push(record)
		} else {
			message.warning('该记录已存在')
		}
	}

	// 添加全部
	const addAllPageRecord = () => {
		let newArray = selectedData.value.concat(tableData.value)
		let list = []
		for (let item1 of newArray) {
			let flag = true
			for (let item2 of list) {
				if (item1.id === item2.id) {
					flag = false
				}
			}
			if (flag) {
				list.push(item1)
			}
		}
		selectedData.value = list

	}
	// 删减记录
	const delRecord = (record) => {
		remove(selectedData.value, (item) => item.id === record.id)
	}
	// 删减记录
	const delAllRecord = () => {
		selectedData.value = []
	}
	// 点击树查询
	const treeSelect = (selectedKeys) => {
		searchFormState.value.current = 0
		if (selectedKeys.length > 0) {
			searchFormState.value.productionCategoriesId = selectedKeys.toString()
		} else {
			delete searchFormState.value.productionCategoriesId
		}
		loadData()
	}
	// 确定
	const handleOk = () => {
		console.log(selectedData.value)
		emit('onBack', selectedData.value)
		handleClose()
	}
	// 重置
	const reset = () => {
		delete searchFormState.value.searchKey
		loadData()
	}
	const handleClose = () => {
		searchFormState.value = {}
		tableRecordNum.value = 0
		tableData.value = []
		current.value = 0
		pageSize.value = 20
		total.value = 0
		selectedData.value = []
		visible.value = false
	}
	const filterSupplierChange = () => {
		//Todo
		searchFormState.value.productionSupplier = props.productionSupplier
		loadData()
	}
	watch(
		() => props.value,
		(newValue) => {
			if (!isEmpty(props.value)) {

			} else {
				selectedData.value = []
			}
		},
		{
			immediate: true // 立即执行
		}
	)
	defineExpose({
		showProductionsPlusModal
	})
</script>
<style lang="less" scoped>
	.xn-mr-5 {
		margin-right: 5px;
	}
	.xn-mr-10 {
		margin-right: 10px;
	}
	.selectorTreeDiv {
		max-height: 500px;
		overflow: auto;
	}
	.ant-form-item {
		margin-bottom: 0 !important;
	}
	.user-table {
		overflow: auto;
		max-height: 450px;
	}

	.user-container {
		display: flex;
		align-items: center; /* 垂直居中 */
		flex-direction: column;
		margin-right: 10px;
		text-align: center;
	}
	.user-avatar {
		width: 30px;
		border-radius: 50%; /* 设置为50%以创建圆形头像 */
	}
	.user-name {
		font-size: 12px;
		max-width: 50px;
		white-space: nowrap;
		overflow: hidden;
	}
	.user-delete {
		z-index: 99;
		color: rgba(0, 0, 0, 0.25);
		position: relative;
		display: flex;
		flex-direction: column;
	}
	.delete-icon {
		position: absolute;
		right: -2px;
		z-index: 5;
		top: -3px;
		cursor: pointer;
		visibility: hidden;
	}
	.show-delete-icon {
		visibility: visible;
	}
</style>
